import 'package:flutter/material.dart';
import 'dart:io';
import 'api_service.dart';
import 'api_response.dart';

/// 网络请求使用示例
/// 这个文件展示了如何使用 ApiService 进行各种网络请求
class NetworkExample {
  static final ApiService _apiService = ApiService();

  /// 示例1: 用户登录
  static Future<void> loginExample() async {
    try {
      final response = await _apiService.login('admin', 'bella_123');

      if (response.statusCode == 200) {
        final apiResponse = ApiResponse.fromJson(
          response.data,
          (json) => json, // 这里可以根据实际返回数据结构定义具体的模型
        );

        if (apiResponse.success) {
          print('登录成功: ${apiResponse.message}');
          // 处理登录成功逻辑
        } else {
          print('登录失败: ${apiResponse.message}');
        }
      }
    } catch (e) {
      print('登录请求异常: $e');
    }
  }

  /// 示例2: 保存用户画像
  static Future<void> saveProfileExample() async {
    try {
      final profileData = {
        'stage': '初中',
        'grade': '八年级',
        'subjects': ['数学', '英语'],
        'learning_goal': '提升数学成绩20分',
      };

      final response = await _apiService.saveUserProfile(profileData);

      if (response.statusCode == 200) {
        print('用户画像保存成功');
      }
    } catch (e) {
      print('保存用户画像失败: $e');
    }
  }

  /// 示例3: 保存用户额外信息
  static Future<void> saveUserExtraInfoExample({
    required String grade,
    required String volume,
    required List<String> subjects,
    required String goals,
  }) async {
    try {
      final extraInfoData = {
        'grade': grade,
        'volume': volume,
        'subjects': subjects.join('/'),
        'goals': goals,
      };

      final response = await _apiService.saveUserExtraInfo(extraInfoData);

      if (response.statusCode == 200) {
        print('用户额外信息保存成功');
      }
    } catch (e) {
      print('保存用户额外信息失败: $e');
    }
  }

  /// 示例4: OCR识别图片
  static Future<void> ocrExample(File imageFile) async {
    try {
      final response = await _apiService.ocrRecognize(imageFile);

      if (response.statusCode == 200) {
        final result = response.data;
        print('OCR识别结果: $result');
        // 处理识别结果
      }
    } catch (e) {
      print('OCR识别失败: $e');
    }
  }

  /// 示例5: 获取AI讲解
  static Future<void> getExplanationExample() async {
    try {
      final response = await _apiService.getExplanation(
        question: '这道二次函数题目怎么解？',
        stage: '初中',
        subject: '数学',
      );

      if (response.statusCode == 200) {
        final explanation = response.data;
        print('AI讲解: $explanation');
      }
    } catch (e) {
      print('获取AI讲解失败: $e');
    }
  }

  /// 示例6: 获取学习统计
  static Future<void> getStatsExample() async {
    try {
      final response = await _apiService.getLearningStats(
        period: 'week',
        subject: '数学',
      );

      if (response.statusCode == 200) {
        final stats = LearningStats.fromJson(response.data);
        print('学习统计: 总时长${stats.totalStudyTime}分钟，正确率${stats.accuracy}%');
      }
    } catch (e) {
      print('获取学习统计失败: $e');
    }
  }

  /// 示例7: 文件上传
  static Future<void> uploadFileExample(File file) async {
    try {
      final response = await _apiService.uploadFile(file);

      if (response.statusCode == 200) {
        final result = response.data;
        print('文件上传成功: ${result['url']}');
      }
    } catch (e) {
      print('文件上传失败: $e');
    }
  }

  /// 示例8: 获取错题列表（带分页）
  static Future<void> getMistakesExample() async {
    try {
      final response = await _apiService.getMistakes(
        subject: '数学',
        status: 'pending',
        page: 1,
        limit: 10,
      );

      if (response.statusCode == 200) {
        final paginatedResponse = PaginatedResponse.fromJson(
          response.data,
          (json) => json, // 这里可以定义具体的错题模型
        );

        print(
          '错题列表: 共${paginatedResponse.totalItems}条，当前第${paginatedResponse.currentPage}页',
        );
        print('错题数据: ${paginatedResponse.data}');
      }
    } catch (e) {
      print('获取错题列表失败: $e');
    }
  }

  /// 示例9: 获取用户额外信息
  static Future<void> getUserExtraInfoExample() async {
    try {
      final response = await _apiService.getUserExtraInfo();

      if (response.statusCode == 200) {
        print('✅ 获取用户额外信息成功: ${response.data}');
      }
    } catch (e) {
      print('❌ 获取用户额外信息失败: $e');
    }
  }
}

/// 在Widget中使用网络请求的示例
class NetworkExampleWidget extends StatefulWidget {
  const NetworkExampleWidget({super.key});

  @override
  State<NetworkExampleWidget> createState() => _NetworkExampleWidgetState();
}

class _NetworkExampleWidgetState extends State<NetworkExampleWidget> {
  bool _isLoading = false;
  String _result = '';

  Future<void> _testLogin() async {
    setState(() {
      _isLoading = true;
      _result = '正在登录...';
    });

    try {
      await NetworkExample.loginExample();
      setState(() {
        _result = '登录测试完成';
      });
    } catch (e) {
      setState(() {
        _result = '登录测试失败: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('网络请求示例')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            ElevatedButton(
              onPressed: _isLoading ? null : _testLogin,
              child:
                  _isLoading
                      ? const CircularProgressIndicator()
                      : const Text('测试登录'),
            ),
            const SizedBox(height: 16),
            Text(_result),
          ],
        ),
      ),
    );
  }
}
